package cn.tedu.vrd.filter;

import cn.tedu.vrd.vo.User;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "MyFilter", urlPatterns = {"/send.html","/product/delete","/admin.html"})
public class MyFilter implements Filter {
    //初始化过滤器时执行的方法
    public void init(FilterConfig config) throws ServletException {
    }

    //销毁过滤器时执行的方法
    public void destroy() {
    }

    //执行Controller之前和之后执行的方法
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        //将父类类型强转为子类类型
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        //获取Session对象
        HttpSession session = req.getSession();
        //获取登录成功时保存的用户对象
        User u = (User) session.getAttribute("u");
        if (u != null){ //已登录
            chain.doFilter(request, response); //放行 执行Controller
        }else {
            resp.sendRedirect("/login.html"); //重定向到登录页面
        }
        // 1 请求资源之前
//        chain.doFilter(request, response); //放行 执行Controller
        // 2 请求资源之后
    }
}
